package ru.royalgatemagazine.app.show.page;

import ru.royalgatemagazine.app.Debug;
import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.webkit.WebView;

public class MWebView extends WebView {
	
	private GestureDetector mDetector;
    private static final int SWIPE_MIN_DISTANCE = 120;//220;//120;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;//3200;//200;
	
	private class MSimpleOnGestureListener extends GestureDetector.SimpleOnGestureListener{
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
			Debug.log("onFling");
			Debug.log("velocityX"+velocityX);
			int dx = (int) (e2.getX() - e1.getX());
			if (
					Math.abs(dx) > SWIPE_MIN_DISTANCE 
					&& Math.abs(velocityX) > Math.abs(velocityY)
					&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY
				) {
				if (velocityX > 0) {
					mController.pageLeft();
				} else {
					mController.pageRight();
				}
				Debug.log(true);
				return true;
			} else {
				Debug.log(false);
				return false;
			}
		}
	}
	
	private PageController mController = new PageController() {
		
		@Override
		public void pageRight() {
		}
		
		@Override
		public void pageLeft() {
		}
		
		@Override
		public void onPageClick(int page) {
		}
		
		@Override
		public void onHeaderButtonMapClick() {
		}
		
		@Override
		public void onHeaderButtonCatalogClick() {
		}

		@Override
		public void hideMap() {
		}
		
	};
	
	public MWebView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		mDetector = new GestureDetector(context, new MSimpleOnGestureListener());
	}
	public MWebView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mDetector = new GestureDetector(context, new MSimpleOnGestureListener());
	}
	public MWebView(Context context) {
		super(context);
		mDetector = new GestureDetector(context, new MSimpleOnGestureListener());
	}
	
	public void setListener(PageController controller){
		if(controller==null){
			throw new IllegalArgumentException("PageController controller==null");
		}
		mController = controller;
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		Debug.log("onTouchEvent");
		boolean detected = mDetector.onTouchEvent(ev);
		mController.hideMap();
		boolean consumed =  super.onTouchEvent(ev);
		return consumed;
	}
}
